/**
 * Created by enroll on 2018/6/28.
 */
import {Component, ChangeDetectorRef, Output, EventEmitter} from "@angular/core";
import { NavController } from 'ionic-angular';
import { ActionSheetController } from 'ionic-angular';
import {Camera, CameraOptions} from '@ionic-native/camera';
import { Device } from "@ionic-native/device";
import {Observable} from "rxjs";
import { Platform } from "ionic-angular";

declare let window: {
  requestFileSystem: any,
  resolveLocalFileSystemURL: any
};

declare enum LocalFileSystem {
  PERSISTENT= 0,
  TEMPORARY= 1
}

declare let cordova: {
  file: any
};

@Component({
  selector: 'upload-file',
  templateUrl: 'upload-file.component.html'
})
export class UploadFileComponent {
    @Output("getResponse") getResponse = new EventEmitter<any>();
    isChrome: boolean = false;

  constructor(
    public navCtrl: NavController,
    private camera: Camera,
    private device: Device,
    private platform: Platform,
    public ref: ChangeDetectorRef,
    private actionSheetCtrl: ActionSheetController
  ) {
    this.isChrome = this.device.cordova ? false : true;
  }

  // chrome 下获取上传路径
  chromeStartCopy(event) {
    this.getResponse.emit("https://img.alicdn.com/bao/uploaded/TB1qimQIpXXXXXbXFXXSutbFXXX.jpg");
  }

  // copy文件入口
  startCopy(event) {
      return Observable.fromPromise(this.pickOrTakePhoto())
        .flatMap((path: string) => {
          return this.transformPath(path)
            .flatMap((pathed: string) => {
              return this.getFillSystem(pathed);
            });
        })
        .flatMap((fileObject: {
          fileEntry,
          dirEntry,
          originName
        }) => {
          return this.moveFile(fileObject.fileEntry, fileObject.dirEntry, fileObject.originName);
        })
        .subscribe((moveEndPath: string) => {
          if (this.platform.is("ios")) {
            moveEndPath = moveEndPath.replace("file://", "");
          }
          this.getResponse.emit(moveEndPath);
          // this.ref.detectChanges();
        });
  }

  productionImg() {
    //
  }


  // select photo
  pickOrTakePhoto() {
    return new Promise((resolve, reject) => {
      let actionSheet = this.actionSheetCtrl.create({
        title: '',
        buttons: [
          {
            text: '从相册选择照片',
            handler: () => {
              const options: CameraOptions = {
                quality: 50,
                destinationType: this.camera.DestinationType.FILE_URI,
                sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
                mediaType: this.camera.MediaType.PICTURE,
                allowEdit: false,
                correctOrientation: true,
                encodingType: this.camera.EncodingType.JPEG,
                targetWidth: 750,
                targetHeight: 1334
              };
              this.camera.getPicture(options).then((path) => {
                resolve(path);
              }, (err) => {
                reject(err);
              });
            }
          }, {
            text: '拍照',
            handler: () => {
              const options: CameraOptions = {
                quality: 50,
                destinationType: this.camera.DestinationType.FILE_URI,
                sourceType: this.camera.PictureSourceType.CAMERA,
                encodingType: this.camera.EncodingType.JPEG,
                mediaType: this.camera.MediaType.PICTURE,
                allowEdit: false,
                correctOrientation: true
              };
              this.camera.getPicture(options).then((path) => {
                resolve(path);
              }, (err) => {
                reject(err);
              });
            }
          }, {
            text: '取消',
            role: 'cancel',
            handler: () => {
              reject();
            }
          }
        ]
      });
      actionSheet.present();
    });
  }


// 原始图片地址转换
  private transformPath(path) {
    return Observable.create((subscriber) => {
      if (!path || path === "cancel") {
        subscriber.error(false);
      } else {
        subscriber.next(path.split("?")[0]);
        subscriber.complete();
      }
    });
  }

  // 打开文件系统
  private getFillSystem(path, defineDir: string = 'wudangImgDir') {
    return Observable.create((subscriber) => {
      window.resolveLocalFileSystemURL(path, (fileEntry) => {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, (fs) => {
          fs.root.getDirectory(defineDir, {create: true}, (dirEntry) => {
            subscriber.next({
              fileEntry: fileEntry,
              dirEntry: dirEntry,
              originName: encodeURI(fileEntry.name)
            });
            subscriber.complete();
          });
        }, (e) => {
          console.log("文件系统加载失败！", e);
          subscriber.error(e);
        });
      }, (e) => {
        console.log("打开文件系统错误" , e);
        subscriber.error(e);
      });
    });
  }

  // start move
  private moveFile(fileEntry, dirEntry, originName) {
    return Observable.create((subscriber) => {
      dirEntry.getFile(originName, {create: false, exclusive: false}, (dirEntryExist) => {
        console.log("是否是个文件？" + dirEntryExist.isFile.toString());
        if (fileEntry.isFile.toString() === "true") {
          subscriber.next(dirEntry.nativeURL + originName);
          subscriber.complete();
        }
      }, (noExist) => {
        fileEntry.copyTo(dirEntry, originName, () => {
          console.log(dirEntry, "--move Success");
          subscriber.next(dirEntry.nativeURL + originName);
          subscriber.complete();
          // that.test = dirEntry.nativeURL + "temp.png";
        }, (e) => {
          console.log("move Error");
          subscriber.error(e);
        });
      });
    });
  }

}
